{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 输出9x9乘法口诀表\n",
    "for i in range(1, 10):\n",
    "    for j in range(1, i + 1):\n",
    "        print(f\"{j}*{i}={i*j}\", end=\"\\t\")\n",
    "    print()  # 换行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "ename": "",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m运行具有“Python 3.14.0”的单元格需要ipykernel包。\n",
      "\u001b[1;31m运行以下命令，将 \"ipykernel\" 安装到 Python 环境中。\n",
      "\u001b[1;31m命令: \"\"c:/Program Files/Python314/python.exe\" -m pip install ipykernel -U --user --force-reinstall\""
     ]
    }
   ],
   "source": [
    "def prime_factorization(n):\n",
    "    # 初始化一个空列表来存储质因数\n",
    "    factors = []\n",
    "    \n",
    "    # 处理2的因数\n",
    "    while n % 2 == 0:\n",
    "        factors.append(2)\n",
    "        n = n // 2\n",
    "    \n",
    "    # 处理奇数因数，从3开始，一直检查到sqrt(n)\n",
    "    for i in range(3, int(n**0.5) + 1, 2):\n",
    "        while n % i == 0:\n",
    "            factors.append(i)\n",
    "            n = n // i\n",
    "    \n",
    "    # 如果n仍然是一个质数且大于2\n",
    "    if n > 2:\n",
    "        factors.append(n)\n",
    "    \n",
    "    # 将质因数列表转换为字符串并打印\n",
    "    print(f\"{factors[0]}\", end=\"\")  # 打印第一个质因数，不添加乘号\n",
    "    for factor in factors[1:]:\n",
    "        print(f\"*{factor}\", end=\"\")  # 对于后续的质因数，添加乘号\n",
    "    print()  # 打印换行符以结束输出\n",
    "\n",
    "# 示例使用\n",
    "number = 90\n",
    "prime_factorization(number)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 获取用户输入，并确保其为不多于6位的正整数\n",
    "try:\n",
    "    num = int(input(\"请输入一个不多于6位的正整数: \"))\n",
    "    if num <= 0 or num > 999999:\n",
    "        raise ValueError(\"输入的数字不符合要求，请确保它是一个不多于6位的正整数。\")\n",
    "except ValueError as e:\n",
    "    print(e)\n",
    "else:\n",
    "    # 判断数字的位数\n",
    "    num_digits = len(str(num))\n",
    "    print(f\"{num} 是一个 {num_digits} 位数。\")\n",
    "    \n",
    "    # 将数字转换为字符串，以便逆序处理\n",
    "    num_str = str(num)\n",
    "    \n",
    "    # 逆序打印每一位数字\n",
    "    reversed_digits = num_str[::-1]\n",
    "    print(\"逆序打印出的各位数字为:\", reversed_digits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 获取用户输入的数字a（确保为单个数字）和累加项的个数n\n",
    "try:\n",
    "    a = int(input(\"请输入一个数字（0-9）: \"))\n",
    "    if a < 0 or a > 9:\n",
    "        raise ValueError(\"输入的不是一个有效的单个数字。\")\n",
    "    n = int(input(\"请输入要累加的项数: \"))\n",
    "    if n <= 0:\n",
    "        raise ValueError(\"累加的项数必须为正整数。\")\n",
    "except ValueError as e:\n",
    "    print(e)\n",
    "else:\n",
    "    # 初始化累加和s\n",
    "    s = 0\n",
    "    # 当前的累加项，从a开始，每次循环都会在其后添加一个a\n",
    "    current_term = 0\n",
    "    \n",
    "    # 循环n次，计算每一项并累加到s中\n",
    "    for _ in range(n):\n",
    "        # 更新当前累加项，例如：0 -> 2, 2 -> 22, 22 -> 222, ...\n",
    "        current_term = current_term * 10 + a\n",
    "        # 将当前累加项加到总和中\n",
    "        s += current_term\n",
    "    \n",
    "    # 输出结果\n",
    "    print(f\"累加和 s = {s}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fraction_sequence_sum(n):\n",
    "    # 初始化前两个分数的分子和分母\n",
    "    numerator_prev1, numerator_prev2 = 2, 1\n",
    "    denominator_prev = 1\n",
    "    \n",
    "    # 初始化总和\n",
    "    total_sum = 0\n",
    "    \n",
    "    # 循环计算前N项的和\n",
    "    for i in range(n):\n",
    "        # 当前项的分子是前两项分子的和\n",
    "        current_numerator = numerator_prev1 + numerator_prev2\n",
    "        # 当前项的分母是前一项的分子\n",
    "        current_denominator = numerator_prev1\n",
    "        \n",
    "        # 将当前分数加到总和中（使用浮点数相加，因为结果可能不是整数）\n",
    "        # 注意：这里使用浮点数相加可能会导致轻微的精度损失，但在这个问题中通常是可以接受的\n",
    "        # 如果需要更高精度，可以考虑使用Python的fractions.Fraction类\n",
    "        total_sum += current_numerator / current_denominator\n",
    "        \n",
    "        # 更新前两项的分子，为下一次循环做准备\n",
    "        numerator_prev2 = numerator_prev1\n",
    "        numerator_prev1 = current_numerator\n",
    "    \n",
    "    return total_sum\n",
    "\n",
    "# 获取用户输入\n",
    "try:\n",
    "    N = int(input(\"请输入要计算的序列项数N: \"))\n",
    "    if N <= 0:\n",
    "        raise ValueError(\"项数N必须为正整数。\")\n",
    "except ValueError as e:\n",
    "    print(e)\n",
    "else:\n",
    "    # 计算并输出前N项之和\n",
    "    result = fraction_sequence_sum(N)\n",
    "    print(f\"分数序列的前{N}项之和为: {result}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def find_x():\n",
    "    # 遍历所有可能的因子对 (a, b) 使得 a * b = 168\n",
    "    for a in range(1, 169):  # 168的因子范围在1到168之间\n",
    "        b = 168 // a\n",
    "        if a * b == 168:\n",
    "            # 计算 n 和 m\n",
    "            n = (a + b) // 2\n",
    "            m = (b - a) // 2\n",
    "            # 检查 n 和 m 是否为整数（即 a 和 b 的奇偶性是否匹配）\n",
    "            if n == int(n) and m == int(m):\n",
    "                n = int(n)\n",
    "                m = int(m)\n",
    "                # 计算 x\n",
    "                x = n**2 - 368\n",
    "                # 验证 x + 100 是否为完全平方数\n",
    "                if int(m**2) == x + 100:\n",
    "                    return x\n",
    "    return None\n",
    "\n",
    "# 找到满足条件的整数 x\n",
    "x = find_x()\n",
    "print(f\"满足条件的整数是: {x}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rabbit_pairs(month):\n",
    "    if month < 1:\n",
    "        return 0\n",
    "    elif month == 1 or month == 2:\n",
    "        return 1\n",
    "    else:\n",
    "        a, b = 1, 1\n",
    "        for _ in range(3, month + 1):\n",
    "            a, b = b, a + b\n",
    "        return b\n",
    "\n",
    "# 测试函数\n",
    "for month in range(1, 13):  # 计算前12个月的兔子总数\n",
    "    print(f\"第{month}个月的兔子总数为: {rabbit_pairs(month)}对\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def input_matrix():\n",
    "    matrix = []\n",
    "    print(\"请输入一个3x3矩阵（每行三个数字，用空格分隔）：\")\n",
    "    for i in range(3):\n",
    "        row = list(map(int, input().split()))\n",
    "        if len(row) != 3:\n",
    "            print(\"输入错误，请确保每行有三个数字。\")\n",
    "            return input_matrix()  # 递归调用以重新输入\n",
    "        matrix.append(row)\n",
    "    return matrix\n",
    "\n",
    "def diagonal_sum(matrix):\n",
    "    if len(matrix) != 3 or not all(len(row) == 3 for row in matrix):\n",
    "        print(\"输入的不是一个3x3矩阵。\")\n",
    "        return None\n",
    "    \n",
    "    sum_diag = matrix[0][0] + matrix[1][1] + matrix[2][2]  # 主对角线元素之和\n",
    "    sum_anti_diag = matrix[0][2] + matrix[1][1] + matrix[2][0]  # 副对角线元素之和（可选计算）\n",
    "    \n",
    "    # 这里我们只返回主对角线元素之和\n",
    "    return sum_diag\n",
    "\n",
    "# 主程序\n",
    "matrix = input_matrix()\n",
    "result = diagonal_sum(matrix)\n",
    "if result is not None:\n",
    "    print(\"矩阵主对角线元素之和为:\", result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rotate_list(nums, m):\n",
    "    n = len(nums)\n",
    "    # 处理m大于n的情况，取m对n的余数\n",
    "    m = m % n\n",
    "    # 使用切片操作来旋转列表\n",
    "    rotated_nums = nums[-m:] + nums[:-m]\n",
    "    return rotated_nums\n",
    "\n",
    "# 示例用法\n",
    "nums = [1, 2, 3, 4, 5, 6, 7]\n",
    "m = 3\n",
    "rotated = rotate_list(nums, m)\n",
    "print(rotated)  # 输出: [5, 6, 7, 1, 2, 3, 4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calculate_series(n):\n",
    "    if n % 2 == 0:\n",
    "        # 当n为偶数时，计算1/2 + 1/4 + ... + 1/n\n",
    "        return sum(1 / i for i in range(2, n + 1, 2))\n",
    "    else:\n",
    "        # 当n为奇数时，计算1/1 + 1/3 + ... + 1/n\n",
    "        return sum(1 / i for i in range(1, n + 1, 2))\n",
    "\n",
    "# 示例用法\n",
    "n = int(input(\"请输入一个整数n: \"))\n",
    "result = calculate_series(n)\n",
    "print(f\"结果是: {result}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义函数\n",
    "def code1():\n",
    "    print(\"# 输出9x9乘法口诀表\")\n",
    "    for i in range(1, 10):\n",
    "        for j in range(1, i + 1):\n",
    "            print(f\"{j}*{i}={i*j}\", end=\"\\t\")\n",
    "        print()  # 换行\n",
    "\n",
    "def code2():\n",
    "    print(\"# 质因数分解\")\n",
    "    def prime_factorization(n):\n",
    "        factors = []\n",
    "        while n % 2 == 0:\n",
    "            factors.append(2)\n",
    "            n = n // 2\n",
    "        for i in range(3, int(n**0.5) + 1, 2):\n",
    "            while n % i == 0:\n",
    "                factors.append(i)\n",
    "                n = n // i\n",
    "        if n > 2:\n",
    "            factors.append(n)\n",
    "        print(f\"{factors[0]}\", end=\"\")\n",
    "        for factor in factors[1:]:\n",
    "            print(f\"*{factor}\", end=\"\")\n",
    "        print()\n",
    "\n",
    "    number = 90\n",
    "    prime_factorization(number)\n",
    "\n",
    "def code3():\n",
    "    print(\"# 获取用户输入，并确保其为不多于6位的正整数\")\n",
    "    try:\n",
    "        num = int(input(\"请输入一个不多于6位的正整数: \"))\n",
    "        if num <= 0 or num > 999999:\n",
    "            raise ValueError(\"输入的数字不符合要求，请确保它是一个不多于6位的正整数。\")\n",
    "    except ValueError as e:\n",
    "        print(e)\n",
    "    else:\n",
    "        num_digits = len(str(num))\n",
    "        print(f\"{num} 是一个 {num_digits} 位数。\")\n",
    "        \n",
    "        num_str = str(num)\n",
    "        reversed_digits = num_str[::-1]\n",
    "        print(\"逆序打印出的各位数字为:\", reversed_digits)\n",
    "\n",
    "def code4():\n",
    "    print(\"# 获取用户输入的数字a（确保为单个数字）和累加项的个数n\")\n",
    "    try:\n",
    "        a = int(input(\"请输入一个数字（0-9）: \"))\n",
    "        if a < 0 or a > 9:\n",
    "            raise ValueError(\"输入的不是一个有效的单个数字。\")\n",
    "        n = int(input(\"请输入要累加的项数: \"))\n",
    "        if n <= 0:\n",
    "            raise ValueError(\"累加的项数必须为正整数。\")\n",
    "    except ValueError as e:\n",
    "        print(e)\n",
    "    else:\n",
    "        s = 0\n",
    "        current_term = 0\n",
    "        \n",
    "        for _ in range(n):\n",
    "            current_term = current_term * 10 + a\n",
    "            s += current_term\n",
    "    \n",
    "        print(f\"累加和 s = {s}\")\n",
    "\n",
    "def code5():\n",
    "    print(\"# 分数序列求和\")\n",
    "    def fraction_sequence_sum(n):\n",
    "        numerator_prev1, numerator_prev2 = 2, 1\n",
    "        denominator_prev = 1\n",
    "        total_sum = 0\n",
    "        \n",
    "        for i in range(n):\n",
    "            current_numerator = numerator_prev1 + numerator_prev2\n",
    "            current_denominator = numerator_prev1\n",
    "            total_sum += current_numerator / current_denominator\n",
    "            numerator_prev2 = numerator_prev1\n",
    "            numerator_prev1 = current_numerator\n",
    "        \n",
    "        return total_sum\n",
    "\n",
    "    try:\n",
    "        N = int(input(\"请输入要计算的序列项数N: \"))\n",
    "        if N <= 0:\n",
    "            raise ValueError(\"项数N必须为正整数。\")\n",
    "    except ValueError as e:\n",
    "        print(e)\n",
    "    else:\n",
    "        result = fraction_sequence_sum(N)\n",
    "        print(f\"分数序列的前{N}项之和为: {result}\")\n",
    "\n",
    "def code6():\n",
    "    print(\"# 寻找满足条件的整数x\")\n",
    "    def find_x():\n",
    "        for a in range(1, 169):  \n",
    "            b = 168 // a\n",
    "            if a * b == 168:\n",
    "                n = (a + b) // 2\n",
    "                m = (b - a) // 2\n",
    "                if n == int(n) and m == int(m):\n",
    "                    n = int(n)\n",
    "                    m = int(m)\n",
    "                    x = n**2 - 368\n",
    "                    if int(m**2) == x + 100:\n",
    "                        return x\n",
    "        return None\n",
    "\n",
    "    x = find_x()\n",
    "    print(f\"满足条件的整数是: {x}\")\n",
    "\n",
    "def code7():\n",
    "    print(\"# 斐波那契数列\")\n",
    "    def rabbit_pairs(month):\n",
    "        if month < 1:\n",
    "            return 0\n",
    "        elif month == 1 or month == 2:\n",
    "            return 1\n",
    "        else:\n",
    "            a, b = 1, 1\n",
    "            for _ in range(3, month + 1):\n",
    "                a, b = b, a + b\n",
    "            return b\n",
    "\n",
    "    for month in range(1, 13):  \n",
    "        print(f\"第{month}个月的兔子总数为: {rabbit_pairs(month)}对\")\n",
    "\n",
    "def code8():\n",
    "    print(\"# 3x3矩阵主对角线元素之和\")\n",
    "    def input_matrix():\n",
    "        matrix = []\n",
    "        print(\"请输入一个3x3矩阵（每行三个数字，用空格分隔）：\")\n",
    "        for i in range(3):\n",
    "            row = list(map(int, input().split()))\n",
    "            if len(row) != 3:\n",
    "                print(\"输入错误，请确保每行有三个数字。\")\n",
    "                return input_matrix()  # 递归调用以重新输入\n",
    "        matrix.append(row)\n",
    "        return matrix\n",
    "\n",
    "    def diagonal_sum(matrix):\n",
    "        if len(matrix) != 3 or not all(len(row) == 3 for row in matrix):\n",
    "            print(\"输入的不是一个3x3矩阵。\")\n",
    "            return None\n",
    "        \n",
    "        sum_diag = matrix[0][0] + matrix[1][1] + matrix[2][2]\n",
    "        return sum_diag\n",
    "\n",
    "    matrix = input_matrix()\n",
    "    result = diagonal_sum(matrix)\n",
    "    if result is not None:\n",
    "        print(\"矩阵主对角线元素之和为:\", result)\n",
    "\n",
    "def code9():\n",
    "    print(\"# 旋转数组\")\n",
    "    def rotate_list(nums, m):\n",
    "        n = len(nums)\n",
    "        m = m % n\n",
    "        rotated_nums = nums[-m:] + nums[:-m]\n",
    "        return rotated_nums\n",
    "\n",
    "    nums = [1, 2, 3, 4, 5, 6, 7]\n",
    "    m = 3\n",
    "    rotated = rotate_list(nums, m)\n",
    "    print(rotated)  # 输出: [5, 6, 7, 1, 2, 3, 4]\n",
    "\n",
    "def code10():\n",
    "    print(\"# 计算数列和\")\n",
    "    def calculate_series(n):\n",
    "        if n % 2 == 0:\n",
    "            return sum(1 / i for i in range(2, n + 1, 2))\n",
    "        else:\n",
    "            return sum(1 / i for i in range(1, n + 1, 2))\n",
    "\n",
    "    n = int(input(\"请输入一个整数n: \"))\n",
    "    result = calculate_series(n)\n",
    "    print(f\"结果是: {result}\")\n",
    "\n",
    "# 创建字典\n",
    "code_blocks = {\n",
    "    1: code1,\n",
    "    2: code2,\n",
    "    3: code3,\n",
    "    4: code4,\n",
    "    5: code5,\n",
    "    6: code6,\n",
    "    7: code7,\n",
    "    8: code8,\n",
    "    9: code9,\n",
    "    10: code10\n",
    "}\n",
    "\n",
    "# 获取用户输入\n",
    "user_input = int(input(\"请输入数字选择代码（1-10）：\"))\n",
    "\n",
    "# 检查输入是否有效\n",
    "if 1 <= user_input <= 10:\n",
    "    # 调用对应的函数\n",
    "    code_blocks[user_input]()\n",
    "else:\n",
    "    print(\"输入的数字不在范围内，请重新输入。\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.14.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
